﻿#region Using directives
using System;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProcolDemo.AICore;
using ProcolDemo.Geolocation;
using ProcolDemo.I18N;
using ProcolDemo.IdeasReference;
using ProcolDemo.Ratings;
using ProcolDemo.User;
using Reimers.Map;

#endregion

namespace ProcolDemo {
    public partial class ViewProfile : Page {
        private readonly I18NService I18N = new I18NService();

        protected void Page_Load(object sender, EventArgs e) {
            if (!Common.IsUserLoggedIn(Session))
                Response.Redirect("Default.aspx");

            var userService = new UserService();

            Common.FillI18NStrings(this, Session);

            int uidSession = Common.GetUserId(Session);
            int uidRequest = Common.GetUserId(Request);

            if (uidRequest < 0) {
                var MP = (MasterPage)Master;
                MP.PopupError.Show();
            } else {
                lblProfileInfo.Text = String.Format(I18N.GetTextAccordingToUserId(uidSession, "PROFILE_INFO"),
                                                    userService.GetUserUsername(uidRequest));

                #region Update info
                if (IsPostBack) {
                    if (!String.IsNullOrEmpty(getActualMajorId(txtMajors.Text)))
                        userService.SetUserMajor(uidSession, getActualMajorId(txtMajors.Text));

                    if (!String.IsNullOrEmpty(txtNewDOB.Text)) {
                        DateTime dt = DateTime.Parse(txtNewDOB.Text);
                        userService.SetUserDOB(uidSession, dt);
                        txtNewDOB_CalendarExtender.SelectedDate = dt;

                        txtNewDOB.Visible = false;
                    }
                }
                #endregion

                #region Get/set user rating
                var ratingService = new RatingService();

                // Just added rating
                if (IsPostBack)
                    ratingService.AddUserRating(uidSession, uidRequest, UserRating.CurrentRating);

                try {
                    var rating = ratingService.GetUserRating(uidRequest);

                    UserRating.CurrentRating = rating;
                } catch (InvalidOperationException) {
                    UserRating.CurrentRating = 0;
                }
                #endregion

                #region Get user info
                bool ownProfile = (uidRequest == uidSession);
                DateTime dob = userService.GetUserDOB(uidRequest);

                txtMajors.BorderStyle = ownProfile ? BorderStyle.Dashed : BorderStyle.None;
                txtMajors.ReadOnly = !ownProfile;

                if (!ownProfile) {
                    txtMajors.CssClass = "nobackground";
                    AUTO_PROFILE_CHANGEINFO.Visible = false;
                    AUTO_PROFILE_CHANGEPASS.Visible = false;
                    AUTO_PROFILE_MANAGEINT.Visible = false;
                    UserRating.ReadOnly = false;
                } else {
                    imgCalendar.Visible = true;
                }

                txtMajors.Text = userService.GetUserMajor(uidRequest, Common.GetUserLanguage(uidSession));
                imgGender.Src = Common.GetUserGender(uidRequest) == Common.Gender.Male
                                        ? "/images/male.png"
                                        : "/images/female.png";
                lblEmail.Text = userService.GetUserMail(uidRequest);
                profileEmail.HRef = String.Format("mailto:{0}", lblEmail.Text);
                lblName.Text = userService.GetUserName(uidRequest);
                lblAge.Text = String.Format(I18N.GetTextAccordingToUserId(uidSession, "PROFILE_AGESTR"), GetAge(dob),
                                            dob.ToShortDateString());
                lblAge.ToolTip = GetAge(dob, uidSession);
                #endregion

                #region Projects
                IntString[] projects = userService.GetProjects(uidRequest);

                dataProjects.DataSource = projects;
                dataProjects.DataBind();
                #endregion

                #region Ideas
                // TODO: Change
                var ideasService = new IdeasService();
                lblNumIdeas.Text = ideasService.GetNumberOfIdeas(uidRequest).ToString();
                #endregion

                #region Interests
                dataInterests.DataSource = userService.GetUserInterests(uidRequest, Common.GetUserLanguage(uidSession));
                dataInterests.DataBind();
                #endregion

                const string strKey = "calendarExtenderPostback";
                if (!ClientScript.IsClientScriptBlockRegistered(GetType(), strKey)) {
                    String strScript = String.Format("function calendarExtenderPostback(e) {{ {0} }}",
                                                     ClientScript.GetPostBackEventReference(btnCalendar, String.Empty));
                    ClientScript.RegisterClientScriptBlock(GetType(), strKey, strScript, true);
                }

                #region Location
                String lastIp = userService.GetLastIp(uidRequest);
                var geoService = new GeolocationService();

                if (!String.IsNullOrEmpty(lastIp)) {
                    String[] location = geoService.GetGeoInfo(lastIp);
                    // Lat, Long
                    double latitude;
                    double longitude;

                    if (Double.TryParse(location[0], out latitude) && Double.TryParse(location[1], out longitude)) {
                        GMap.Latitude = latitude;
                        GMap.Longitude = longitude;
                        GMap.Zoom = 10;
                        GMap.Controls.Add(new Reimers.Map.Controls.GoogleSmallMapTypeControl("smc"));
                        GMap.Controls.Add(new Reimers.Map.Controls.GoogleSmallMapControl("sc"));

                        var icon1 = new GoogleIcon("green", "http://www.reimers.dk/images/icons/icong.png", "http://www.google.com/mapfiles/shadow50.png", new GoogleSize(20, 34), new GoogleSize(37, 34), new GooglePoint(9, 34), new GooglePoint(0, 0), new GooglePoint(9, 34));
                        var p1 = new GoogleLatLng(latitude, longitude);
                        var m = new GoogleMarker("UserLoc", p1) { MarkerText = "X marks the spot", Options = new GoogleMarkerOptions("Westminster", icon1) };
                        GMap.Icons.Add(icon1);
                        GMap.Overlays.Clear();
                        GMap.Overlays.Add(m);
                    }
                }
                #endregion

                #region AI Matching
                var matchingService = new MatchingService();
                var similarUsers = matchingService.GetSimilarUsers(uidRequest, 10);

                dataSimilarUsers.DataSource = similarUsers;
                dataSimilarUsers.DataBind();
                #endregion
            }

            txtMajors_AutoCompleteExtender.CompletionSetCount = Common.GetUserLanguage(uidRequest);
        }

        private static int GetAge(DateTime date) {
            int years = DateTime.Now.Year - date.Year;

            date = date.AddYears(years);

            if (DateTime.Now.CompareTo(date) < 0)
                years--;

            return years;
        }

        private String GetAge(DateTime date, int uid) {
            int years = DateTime.Now.Year - date.Year;
            int months;

            if (DateTime.Now < date.AddYears(years) && years != 0)
                --years;

            date = date.AddYears(years);
            if (date.Year == DateTime.Now.Year)
                months = DateTime.Now.Month - date.Month;
            else
                months = (12 - date.Month) + DateTime.Now.Month;

            if (DateTime.Now < date.AddMonths(months) && months != 0)
                --months;

            date = date.AddMonths(months);
            int days = (DateTime.Now - date).Days;

            return String.Format(I18N.GetTextAccordingToUserId(uid, "PROFILE_DOBSTR"), years, months, days);
        }

        protected void txtMajors_TextChanged(object sender, EventArgs e) {
        }

        private static String getActualMajorId(String str) {
            var re = new Regex(@"^(?<major>\w{3,})(?: -)?");
            Match m = re.Match(str);

            if (m.Success)
                return m.Groups["major"].ToString();

            return String.Empty;
        }

        protected void btnCalendar_Click(object sender, EventArgs e) {
            var userService = new UserService();
            int uidSession = Common.GetUserId(Session);

            DateTime dt = DateTime.Parse(txtNewDOB.Text);
            userService.SetUserDOB(uidSession, dt);
        }

        protected void imgCalendar_Click(object sender, ImageClickEventArgs e) {
            var userService = new UserService();
            int uidSession = Common.GetUserId(Session);

            txtNewDOB_CalendarExtender.SelectedDate = userService.GetUserDOB(uidSession);
            txtNewDOB.Visible = true;
            txtNewDOB_CalendarExtender.Animated = true;
        }
    }
}